package net.ib.mtalk.ui.attachment.vcard;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import net.ib.mntalk.protocol.Common.UserMessage;
import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseListActivity;
import net.ib.mtalk.constant.MTalkConstant;
import net.ib.mtalk.database.helper.ChatDatabaseHelper;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 받은 VCard를 Parsing 하여서 보여주고 받은 내용에 대한 작업을 한다.
 * 
 * @author happy2v
 *
 * @version 0.2.2
 * @since 2011-05-17
 * 
 */
public class VCardReadActivity extends BaseListActivity {

	public static final String INTENT_MESSAGE_UUID_MSB = "intent_message_uuid_msb"; 
	public static final String INTENT_MESSAGE_UUID_LSB = "intent_message_uuid_lsb"; 
	
	private static ContactStruct vCardStruct;
	private List<VCardListItemStruct> mItems;
	
	private String vCardStr;
	
	Context mContext;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_vcard_list);
		
		mContext = this;
		
		mItems = new ArrayList<VCardListItemStruct>();
		
		initVal();
		
		if(vCardStr == null){
			finish();
		}
		
		try {
			parseVcard();
		} catch (Exception e) {
			MTalkLogWriter.e(e);
		}
	}
	
	// 값을 설정한다.
	private void initVal(){
		Bundle extras = getIntent().getExtras();
		
		long clientMsgUuidMsb = 0L;
		long clientMsgUuidLsb = 0L;
		
		if(extras != null && extras.containsKey(INTENT_MESSAGE_UUID_MSB)){
			clientMsgUuidMsb = extras.getLong(INTENT_MESSAGE_UUID_MSB);
		}else{
			return;
		}
		if(extras != null && extras.containsKey(INTENT_MESSAGE_UUID_LSB)){
			clientMsgUuidLsb = extras.getLong(INTENT_MESSAGE_UUID_LSB);
		}else{
			return;
		}
		
		UserMessage userMessage = ChatDatabaseHelper.getUserMessage(mContext, GpbSupport.makeUuidMsg(clientMsgUuidMsb, clientMsgUuidLsb));
		
		if(userMessage == null 
				|| !userMessage.hasAttachment()
				|| !userMessage.getAttachment().hasContent()
				|| !(userMessage.getAttachment().getMimeType().equals(MTalkConstant.MIME_TYPE_VCARD))){
			return;
		}

		vCardStr = userMessage.getAttachment().getContent().toStringUtf8();
	}
	
	// vCardStr 을 파싱하여서 아이템을 만든다.
	private void parseVcard() throws Exception{
		if(vCardStr == null){
			return;
		}
		VCardParser mnParser= new VCardParser();
		vCardStruct = mnParser.parse(vCardStr);
		
		bindView(vCardStruct);
	}
	
	private void bindView(ContactStruct contactInfo) {
		ImageView vCardProfileImg = (ImageView)findViewById(R.id.vcard_profile_icon);
		TextView vCardNameText = (TextView)findViewById(R.id.vcard_name_text);
		ImageView vCardSaveBtn = (ImageView)findViewById(R.id.vcard_send_btn);
		vCardSaveBtn.setImageResource(R.drawable.ic_save_btn);
		
		vCardSaveBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				File checkSDCardDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
				if(!checkSDCardDirectory.canRead()){
					Toast.makeText(mContext, R.string.toast_sdcard_not_found, Toast.LENGTH_SHORT).show();
				}else{
	        		AddVCardDialog dialog = new AddVCardDialog(mContext);
					dialog.show();
				}
			}
		});
		
		vCardStruct = contactInfo;
		
		// 기본 화면을 설정한다.
		// 사진 표시
        if(contactInfo.photoBytes != null){
        	Bitmap photoBmp = null;
		    ByteArrayInputStream byteIn = new ByteArrayInputStream(contactInfo.photoBytes);
		    photoBmp = BitmapFactory.decodeStream(byteIn);
		    vCardProfileImg.setImageBitmap(photoBmp);
        }
        
        // 이름 표시 // 있을때까지 찾아보고 그래도 없으면 기본값을 넣는다.
        if(contactInfo.fullName != null){
        	vCardNameText.setText(contactInfo.fullName);
        }else if(contactInfo.name != null){
        	vCardNameText.setText(contactInfo.name);
        }else{
        	vCardNameText.setText(mContext.getString(R.string.vcard_default_name));
        }
		
        // 뷰를 그려주기 위한 리스트를 만들자.
		mItems = new ArrayList<VCardListItemStruct>();		
		// 필요한 아이템 추가
		if(contactInfo.phoneList != null){
			for(int i = 0; contactInfo.phoneList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_PHONE,
								mContext.getString(VCardConst.getPhoneTypeRes(contactInfo.phoneList.get(i).type)),
								contactInfo.phoneList.get(i).number, i));
			}
		}
		if(contactInfo.emailList != null){
			for(int i = 0; contactInfo.emailList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_EMAIL,
								mContext.getString(VCardConst.getEmailTypeRes(contactInfo.emailList.get(i).type)),
								contactInfo.emailList.get(i).address, i));
			}
		}
		if(contactInfo.postalList != null){
			for(int i = 0; contactInfo.postalList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_POSTAL,
								mContext.getString(VCardConst.getPostalTypeRes(contactInfo.postalList.get(i).type)),
								contactInfo.postalList.get(i).formattedAddress, i));
			}
		}
		if(contactInfo.imList != null){
			for(int i = 0; contactInfo.imList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_IM,
								mContext.getString(VCardConst.getImProtocolRes(contactInfo.imList.get(i).protocol)),
								contactInfo.imList.get(i).data, i));
			}
		}
		if(contactInfo.company != null && !contactInfo.company.equals("")){
			mItems.add(new VCardListItemStruct(ContactStruct.KIND_ORGANIZATION,
						mContext.getString(VCardConst.getOrganizationTypeRes(Organization.TYPE_CUSTOM)),
						contactInfo.company, 0));
		}
		if(contactInfo.noteList != null){
			for(int i = 0; contactInfo.noteList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_NOTE,
								mContext.getString(R.string.vcard_item_note),
								contactInfo.noteList.get(i).note, i));
			}
		}
		
		VCardReadAdapter adapter = new VCardReadAdapter(this, mItems);
		setListAdapter(adapter);
	}
	
	public static ContactStruct getContactInfo(){
		return vCardStruct;
	}
}
